package com.heifeng.cloudshelf.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;

import com.heifeng.cloudshelf.base.MyApp;

public class NetCheck {

    private Handler _handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (1 == msg.what) {
                if (null != mContext) {
                    _handler.sendEmptyMessageDelayed(1, 3500);
                    sendCallBackMessage();
                }
            }
        }
    };

    private void sendCallBackMessage() {
        boolean isConnected = NetUtils.isNetworkConnected(mContext);
        if (null != sparseArray && sparseArray.size() > 0) {
            for (int i = 0; i < sparseArray.size(); i++) {
                OnNetConnectListener onNetConnectListener = sparseArray.get(i);
                if (null != onNetConnectListener) {
                    onNetConnectListener.onConnected(isConnected);
                }else{
                    sparseArray.remove(i);
                }
            }
        }
    }

    private SparseArray<OnNetConnectListener> sparseArray = new SparseArray<>();

    private static boolean isStarted = false;
    private static NetCheck netCheck;
    private static Context mContext;
    private static int count = 0;
//    private OnNetConnectListener onNetConnectListener;


    public static NetCheck getInstance() {
//        WeakReference<Context> contextWeakReference = new WeakReference<Context>(context);
        mContext = MyApp.getInstance().getApplicationContext();
        if (null == netCheck) {
            netCheck = new NetCheck();
        }
        return netCheck;
    }

    public int setOnNetConnectListener(OnNetConnectListener onNetConnectListener) {
//        this.onNetConnectListener = onNetConnectListener;
        sparseArray.put(count, onNetConnectListener);
        count += 1;
        return count - 1;
    }

    public void start() {
        if (!isStarted) {
            isStarted = true;
            _handler.sendEmptyMessage(1);
        }
    }

    public void removeListener(int id){
        if (null != sparseArray && sparseArray.size() > 0) {
            sparseArray.remove(id);
        }
    }

//    public void destory() {
//        if (isStarted) {
//            _handler.removeMessages(1);
//            _handler.removeCallbacksAndMessages(null);
//            sparseArray.clear();
//        }
//    }

    public interface OnNetConnectListener {
        void onConnected(boolean isConnect);
    }
}
